<?php
/**
 * 导入Excel时的地区处理的队列 Handle
 */
namespace App\Commands;

use App\Commands\Command;
use Illuminate\Queue\SerializesModels;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Bus\SelfHandling;
use Illuminate\Contracts\Queue\ShouldQueue;

use App\Models\ExportTempArea;
use App\Models\Area;
use App\Models\Organization;

class ExportArea extends Command implements SelfHandling, ShouldQueue
{
    use InteractsWithQueue, SerializesModels;

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        //
    }

    /**
     * Execute the command.
     *
     * @return void
     */
    public function handle()
    {
        //临时表里的地区记录
        $areas = ExportTempArea::all();
        $temp_area_ids = [];
        foreach ($areas as $value) {
            $province_id = Area::where('title', '=', $value->province)->pluck('area_id');
            $city_id = Area::where('title', 'LIKE', '%' . $value->city . '%')->pluck('area_id');
            $area_id = Area::where('title', 'LIKE', '%' . $value->area . '%')->where('pid', '=', $city_id)->pluck('area_id');

            $org = Organization::find($value->org_id);
            $org->province = $province_id;
            $org->city = $city_id;
            $org->area = $area_id;
            $org->save();
            $temp_area_ids[] = $value->id;
        }
        // 更新organization表里记录后
        ExportTempArea::whereIn('id', $temp_area_ids)->delete();
    }
}
